import { Component } from '@angular/core';
import {
  FormGroup,
  ReactiveFormsModule,
  Validators,
  FormControl,
  FormArray,
  AbstractControl
} from '@angular/forms';

function equalValues(control:AbstractControl){
  const password = control.get('password')?.value;
  const confirmPassword = control.get('confirmPassword')?.value;

  if(password === confirmPassword){
    return null;
  }

  return { passwordsNotEqual : true};

}

@Component({
  selector: 'app-signup',
  imports: [
    ReactiveFormsModule
  ],
  templateUrl: './signup.html',
  styleUrl: './signup.css'
})
export class Signup {
  form = new FormGroup({
    email:new FormControl('',{
      validators:[Validators.email,Validators.required],
    }),

    passwords:new FormGroup({
      password:new FormControl('',{
        validators:[Validators.required,Validators.minLength(6)],
      }),

      confirmPassword:new FormControl('',{
        validators:[Validators.required,Validators.minLength(6)],
      }),
    },
      {
        validators:[equalValues],
      }
      ),


    firstName:new FormControl('',{validators:[Validators.required]}),
    lastName:new FormControl('',{validators:[Validators.required]}),

    address:new FormGroup({
      street:new FormControl('',{validators:[Validators.required]}),
      number:new FormControl('',{validators:[Validators.required]}),
      postalCode:new FormControl('',{validators:[Validators.required]}),
      city:new FormControl('',{validators:[Validators.required]}),
    }),

    source:new FormArray([
      new FormControl(false),
      new FormControl(false),
      new FormControl(false),
    ]),
    role:new FormControl<'student' | 'teacher' | 'employee'| 'founder' | 'other'>('student',[Validators.required]),
    agree:new FormControl(false,{validators:[Validators.required]}),

  })

  get emailIsInvalid(){
    return(
      this.form.controls.email.touched &&
        this.form.controls.email.dirty &&
        this.form.controls.email.invalid
    );
  }



  onSubmit(){
    if(this.form.invalid){
      console.log('invalid');
      return;
    }
    console.log(this.form);
  }

  onReset(){
    this.form.reset();
  }
}
